package com.momalib.ning2_nocode.utils;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.util.Map;

public class YamlUtil {

    public static <T> T parseConfig(File yamlFile, T obj) {
        Yaml yaml = new Yaml();

        Map<String, Object> objectMap = null;
        try {
            objectMap = yaml.load(new FileInputStream(yamlFile));
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在2");
        }

        if (objectMap == null) {
            return obj;
        }

        Field[] objFields = obj.getClass().getDeclaredFields();//字段信息集合
        Field.setAccessible(objFields, true);
        for (Field objField : objFields) {
            String objName = objField.getName();//字段名称
//            Object promptValue = objField.get(t1);//字段值
            String valueType = objField.getType().toString();//字段类型
//            System.out.printf("%s: %s%n", objName, valueType);
            if (objectMap.containsKey(objName)) {
                try {
                    if ("class java.lang.String".equals(valueType)) {
                        objField.set(obj, objectMap.get(objName));
                    } else {
                        objField.set(obj, CommonUtils.json2Obj(CommonUtils.obj2JsonStr(objectMap.get(objName)), objField.getType()));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }

        return obj;
    }

}
